package core

import (
	"fmt"
	"io"
	"sync"
	"time"
)

type Units int64

// 文件大小的单位
const (
	B  Units = 1
	KB       = B << 10
	MB       = KB << 10
	GB       = MB << 10
	TB       = GB << 10
)

var wg sync.WaitGroup

// 显示进度条
func Display(srcPath, destPath, unitStr, pwd string, isBar bool, windowWidth int) (ok bool, err error) {
	defer close(NewProgress().progressChan)
	defer wg.Wait()
	start := time.Now()
	// 创建加密实例
	newEncryptor := NewEncryptor(pwd)
	// 创建进度通道实例
	newProgress := NewProgress()
	wg.Add(1)
	go func() {
		defer wg.Done()
		if err := newEncryptor.Encrypt(srcPath, destPath, newProgress); err != nil {
			// 如果加密出错，通知进度条。
			newProgress.progressChan <- &writeData{err: err}
			fmt.Println(err)
		}
	}()
	bar := new(Bar)

	// 获取收个数据，设置文件大小
	for {
		select {
		case wData, ok := <-newProgress.progressChan:
			if !ok {
				continue
			}
			if wData.fileSize > 0 {
				// 初始化一个进度条
				bar.newOptionWithGraph(0, int64(wData.fileSize), int64(windowWidth), "=")
			}
			if len(wData.data) > 0 {
				bar.Play(int64(len(wData.data)), isBar, unitStr, start)
			}
			if wData.err != nil {
				return false, wData.err
			}
			if wData.eof == io.EOF {
				return true, nil
			}
		default:
			continue
		}
	}

}
